using MediatR;
using Microsoft.EntityFrameworkCore;
using SupplierCustomerManagement.Infrastructure;
using SupplierCustomerManagement.Read.API.Applications.Commands.lambing;
using SupplierCustomerManagement.Read.API.Dtos.Lambing;

namespace SupplierCustomerManagement.Read.API.Applications.CommandHandlters.lambing
{
    public class GetFarmOptionsQueryHandler : IRequestHandler<GetFarmOptionsQuery, List<FarmOptionDto>>
    {
        private readonly SupplierDbContext _db;
        private readonly ILogger<GetFarmOptionsQueryHandler> _logger;

        public GetFarmOptionsQueryHandler(SupplierDbContext db, ILogger<GetFarmOptionsQueryHandler> logger)
        {
            _db = db;
            _logger = logger;
        }

        public async Task<List<FarmOptionDto>> Handle(GetFarmOptionsQuery request, CancellationToken cancellationToken)
        {
            // 基于已有 LambingRecords 去重 FarmId，名称暂用“羊场 {id}”。如果后续有 Farm 表，可替换为真实名称。
            var ids = await _db.LambingRecords
                .AsNoTracking()
                .Select(r => r.FarmId)
                .Distinct()
                .OrderBy(id => id)
                .ToListAsync(cancellationToken);

            // 通过 EF Core 查询 Farms 实体获取真实名称（若存在），否则回退为“羊场 {id}”
            var nameList = await _db.Farms
                .AsNoTracking()
                .Where(f => ids.Contains(f.Id))
                .Select(f => new { f.Id, f.FarmName })
                .ToListAsync(cancellationToken);

            var nameMap = nameList
                .Where(x => !string.IsNullOrWhiteSpace(x.FarmName))
                .ToDictionary(x => x.Id, x => x.FarmName!);

            var options = ids.Select(id => new FarmOptionDto
            {
                id = id,
                name = nameMap.TryGetValue(id, out var nm) && !string.IsNullOrWhiteSpace(nm) ? nm : $"羊场 {id}"
            }).ToList();

            return options;
        }
    }
}
